package com.m3958.firstgwt.server.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import com.google.inject.Inject;
import com.m3958.firstgwt.server.model.BaseModel;
import com.m3958.firstgwt.server.model.WorkFlowProject;
import com.m3958.firstgwt.shared.type.SmartParameterName;

public class WorkFlowProjectDao  extends BaseDao<WorkFlowProject>{
	
	@Inject
	public WorkFlowProjectDao(WorkFlowProjectChangeStrategy task) {
		super(WorkFlowProject.class);
		extraStrategyTask = task;
	}
	
	
	@Override
	public Integer smartCustomCount() {
		return 0;
	}
	
	public WorkFlowProject findByUUID(String uuid){
		try{
			Query q =  emp.get().createNamedQuery(WorkFlowProject.NamedQueries.FIND_PROJECT_BY_UUID);
			q.setParameter(1, uuid);
			return (WorkFlowProject) q.getSingleResult();
		}catch (Exception e) {
			;
		}
		return null;
	}

	@Override
	public List<BaseModel> smartCustomFetch() {
		return null;
	}


	@Override
	public List<WorkFlowProject> smartNamedQueryFetch() {
		try {
			String queryName = getReqPs().getStringValue(SmartParameterName.NAMED_QUERY_NAME, "");
			if(WorkFlowProject.NamedQueries.FIND_BY_USER_ID.equals(queryName)){
				if(getSu().isLogined()){
					Query q = emp.get().createNamedQuery(queryName);
					q.setParameter(1, getSu().getUserId());
					return q.getResultList();
				}
			}else if(WorkFlowProject.NamedQueries.FIND_PROJECTS_BY_UUID.equals(queryName)){
				Query q = emp.get().createNamedQuery(queryName);
				String itemid = getReqPs().getStringValue("_itemId", "");
				q.setParameter(1, "%" + itemid + "%");
				q.setParameter(2, itemid);
				return q.getResultList();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return new ArrayList<WorkFlowProject>();
	}


	@Override
	public Integer smartNamedQueryFetchCount() {
		String queryName = getReqPs().getStringValue(SmartParameterName.NAMED_QUERY_NAME, "");
		if(WorkFlowProject.NamedQueries.FIND_BY_USER_ID.equals(queryName)){
			if(getSu().isLogined()){
				Query q = emp.get().createQuery("SELECT COUNT(DISTINCT w) FROM WorkFlowProject AS w WHERE w.creator.id = " + getSu().getUserId());
				Long c = (Long) q.getSingleResult();
				return c.intValue();
			}
		}else if(WorkFlowProject.NamedQueries.FIND_PROJECTS_BY_UUID.equals(queryName)){
			String itemid = getReqPs().getStringValue("_itemId", "");
			Query q = emp.get().createQuery("SELECT COUNT(DISTINCT w) FROM WorkFlowProject AS w WHERE w.path LIKE ?1 OR w.uuid = ?2");
			q.setParameter(1, "%" + itemid + "%");
			q.setParameter(2, itemid);
			Long c = (Long) q.getSingleResult();
			return c.intValue();
		}
		
		return 0;
	}

}
